from django.db import models

# Create your models here.

class BookInfoManager(models.Manager):
    @classmethod
    def class_method(cls, ):
        pass
    def all(self):
        # 达到过滤已经删除的书籍
        return super().filter(is_delete=False)

    def filter_hot(self):
        # 要取出阅读量在100以上的书籍, 定义为热门书籍
        return super().filter(bread__gte=100, is_delete=False)

    def create_hot(self, btitle, bpub_date):
        # 创建一个热门书籍
        model= self.model  # 指的是 管理器实例 管理的 模型
        book = model()  # 被管理器管理的模型,  self -> mybojects (BookInfoManager 的实例)
        book.btitle = btitle
        book.bpub_date = bpub_date
        book.bread = 100
        book.bcomment = 100
        book.is_delete=False
        book.save()
        return book

# 1.定义类
class BookInfo(models.Model):
    # 2.定义字段
    btitle = models.CharField(max_length=20, verbose_name='名称')
    bpub_date = models.DateField(verbose_name='发布日期')
    bread = models.IntegerField(default=0, verbose_name='阅读量')
    bcomment = models.IntegerField(default=0, verbose_name='评论量')
    is_delete = models.BooleanField(default=False, verbose_name='是否删除')
    image = models.ImageField(upload_to='book', verbose_name='封面', null=True)


    myobjects = BookInfoManager()

    class Meta:
        # 如果不定义 db_table,  生成的表名是  appname_类名小写
        # ormapp_bookinfo
        db_table = 'tb_books'  # 数据库中生成的表名
        verbose_name = '图书'
        verbose_name_plural = verbose_name

    def is_hot(self):
        if self.bread >= 100:
            res = '热门'
        else:
            res = '..'
        return res

    is_hot.short_description = '是否热门'
    is_hot.admin_order_field = 'bread'

    def __str__(self):
        return self.btitle

# 1.定义类
class HeroInfo(models.Model):
    GENDER_CHOICES = (
        (0, 'female'),
        (1, 'male')
    )
    # 2.定义字段
    hname = models.CharField(max_length=20, verbose_name='英雄名字')
    hgender = models.SmallIntegerField(choices=GENDER_CHOICES, default=0, verbose_name='性别')
    hcomment = models.CharField(max_length=200, null=True, blank=True, verbose_name='英雄描述')
    hbook = models.ForeignKey(BookInfo, on_delete=models.CASCADE, verbose_name='书籍')
    is_delete = models.BooleanField(default=False, verbose_name='是否删除')

    def hread(self):
        return self.hbook.bread

    hread.short_description = '阅读量'

    class Meta:
        db_table = 'tb_heros'
        verbose_name = '英雄'
        verbose_name_plural = '英雄联盟'

    def __str__(self):
        return self.hname

class PeopleManager(models.Manager):
    def create_zhang(self, name):
        # 创建一个姓张的人
        model = self.model  # Teacher,  Student
        instance = model(name='张'+name)
        instance.save()
        return instance

class Teacher(models.Model):
    name = models.CharField(max_length=20, verbose_name='姓名')

    myobjects = PeopleManager()

class Student(models.Model):
    name = models.CharField(max_length=20, verbose_name='姓名')

    myobjects = PeopleManager()